package com.gitee.cheungming.search.service;

import cn.hutool.core.util.RandomUtil;
import com.gitee.cheungming.search.doc.GoodsDocument;
import com.gitee.cheungming.search.reposity.GoodsDocumentRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;

import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class TxtToElasticsearch {
    // 配置常量
    private static final String JDBC_URL = "jdbc:mysql://192.168.50.2:3306/mall_goods";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";
    private static final String FILE_PATH = "data/item_profile.txt";
    private static final String DELIMITER = "\t"; // 分隔符，例如"|"
    private static final int BATCH_SIZE = 10000; // 批量插入大小
    private static final int EXPECTED_COLUMNS = 6; // 期望的列数


    @Autowired
    GoodsDocumentRepository goodsDocumentRepository;

    @Autowired
    private ResourceLoader resourceLoader;

    @jakarta.annotation.Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void importData() throws Exception {
        System.out.println("当前工作目录: " + System.getProperty("user.dir"));
        int totalLines = 0;
        int batchCount = 0;
        Resource resource = resourceLoader.getResource("classpath:data/item_profile.txt");
        BufferedReader reader = new BufferedReader(new FileReader(resource.getFile()));
        String line;

        List<GoodsDocument> batch = new ArrayList<>();
        GoodsDocument goodsDocument;


        while ((line = reader.readLine()) != null) {
            try {
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }

                String[] data = line.split(DELIMITER, -1); // 使用-1保留尾部空值

                // 验证数据格式
                if (data.length != EXPECTED_COLUMNS) {
                    throw new IllegalArgumentException(
                            String.format("列数不匹配: 期望%d列，实际%d列", EXPECTED_COLUMNS, data.length));
                }
                /**
                 * 1. 商品标题
                 * 2. 商品url
                 * 3. 价格
                 * 4. 商品描述
                 * 5. 品牌
                 * 6. 对应百分点类目
                 */
                goodsDocument = new GoodsDocument();
                goodsDocument.setGoodsName(data[0].trim());
                goodsDocument.setUrl(data[1].trim());
                String price = data[2].trim();
                if ("".equals(price)) {
                    price = "100.0";
                }
                goodsDocument.setPrice(new BigDecimal(price));
                goodsDocument.setDescription(data[3].trim());
                goodsDocument.setBrand(data[4].trim());
                goodsDocument.setCategory(data[5].trim());
                goodsDocument.setStock(RandomUtil.randomInt(1, 100));
                goodsDocument.setLockedStock(0);
                batch.add(goodsDocument);
                // 设置参数
                batchCount++;

                // 批量执行
                if (batchCount % BATCH_SIZE == 0) {
                    goodsDocumentRepository.saveAll(batch);
                    batch.clear();
                    batchCount = 0;
                    return;
                }
            } catch (Exception e) {
                String errorMsg = String.format("第%d行处理失败: %s - 数据: %s",
                        totalLines, e.getMessage(), line);
                System.err.println(errorMsg);
            }
        }
    }

}
